import { NextRequest, NextResponse } from 'next/server'
import { projectQueries, userProjectLinkQueries, createAuditLog, todoQueries } from '@/lib/database-prisma'
import prisma from '@/lib/database-prisma'
import { getUserFromRequest } from '@/lib/auth-utils'
import type { Project } from '@/types/database'

export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ projectId: string }> }
) {
  try {
    const userInfo = await getUserFromRequest(request)
    if (!userInfo) {
      return NextResponse.json({ error: '未授权' }, { status: 401 })
    }

    const { projectId } = await params
    const projectIdNum = parseInt(projectId)
    
    // 检查项目是否存在
    const projectById = await projectQueries.findById.get(projectIdNum)
    if (!projectById) {
      return NextResponse.json({ error: '项目不存在' }, { status: 404 })
    }

    // 检查用户是否有权限编辑此项目
    const hasAccess = await userProjectLinkQueries.checkUserInProject.get(userInfo.id, projectIdNum)
    if (!hasAccess || hasAccess.count === 0) {
      return NextResponse.json({ error: '您没有权限编辑此项目' }, { status: 403 })
    }

    const body = await request.json()
    const { description, memberIds } = body

    if (!description) {
      return NextResponse.json({ error: '项目简介不能为空' }, { status: 400 })
    }

    if (description.length > 300) {
      return NextResponse.json({ error: '项目简介不能超过300个字符' }, { status: 400 })
    }

    // 更新项目描述（项目名称不允许修改）
    await projectQueries.update.run(description, projectIdNum)

    // 如果提供了成员列表，更新项目成员
    if (memberIds && Array.isArray(memberIds)) {
      // 获取当前项目成员
      const currentMembers = await userProjectLinkQueries.getUsersByProjectId.all(projectIdNum)
      const currentMemberIds = currentMembers.map(m => m.id)
      
      // 确保当前用户始终在成员列表中，处理memberIds为空的情况
      const newMemberIds = memberIds.length > 0 ? memberIds : [userInfo.id] 
      const finalMemberIds = Array.from(new Set([userInfo.id, ...newMemberIds]))
      
      // 找出需要添加的成员
      const membersToAdd = finalMemberIds.filter(id => !currentMemberIds.includes(id))
      
      // 添加新成员
      for (const memberIdToAdd of membersToAdd) {
        try {
          await userProjectLinkQueries.create.run(memberIdToAdd, projectIdNum)
        } catch (err) {
          console.log(`成员 ${memberIdToAdd} 添加失败，可能已存在`)
        }
      }
      
      // 注意：我们不在这里删除成员，删除操作应该通过专门的DELETE端点进行
    }

    // 获取更新后的项目信息
    const updatedProject = await projectQueries.findById.get(projectIdNum)

    // 添加审计日志
    if (updatedProject) {
      try {
        await createAuditLog(
          userInfo.id,
          {
            type: "project",
            name: updatedProject.name,
            id: projectIdNum,
            act: "update", // 操作类型为更新
            details: { description: description }, // 可以记录更新的具体内容
            time: new Date().toISOString(),
          },
          projectIdNum
        )
      } catch (auditError) {
        console.error('创建项目更新审计日志失败:', auditError)
      }
    }

    return NextResponse.json(updatedProject)
  } catch (error) {
    console.error('更新项目失败:', error)
    return NextResponse.json({ error: '更新项目失败' }, { status: 500 })
  }
}

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ projectId: string }> }
) {
  try {
    const userInfo = await getUserFromRequest(request)
    if (!userInfo) {
      return NextResponse.json({ error: '未授权' }, { status: 401 })
    }

    const { projectId } = await params
    const projectIdNum = parseInt(projectId)
    
    const project = await projectQueries.findById.get(projectIdNum)
    
    if (!project) {
      return NextResponse.json({ error: '项目不存在' }, { status: 404 })
    }

    const hasAccess = await userProjectLinkQueries.checkUserInProject.get(userInfo.id, project.id)
    if (!hasAccess || hasAccess.count === 0) {
      return NextResponse.json({ error: '您没有访问此项目的权限' }, { status: 403 })
    }
    
    return NextResponse.json(project)
  } catch (error) {
    console.error('获取项目信息失败:', error)
    return NextResponse.json({ error: '获取项目信息失败' }, { status: 500 })
  }
}

export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ projectId: string }> }
) {
  try {
    const userInfo = await getUserFromRequest(request)
    if (!userInfo) {
      return NextResponse.json({ error: '未授权' }, { status: 401 })
    }

    const { projectId } = await params
    const projectIdNum = parseInt(projectId)
    const project = await projectQueries.findById.get(projectIdNum)
    
    if (!project) {
      return NextResponse.json({ error: '项目不存在' }, { status: 404 })
    }

    // 检查用户是否有权限删除项目
    const hasAccess = await userProjectLinkQueries.checkUserInProject.get(userInfo.id, projectIdNum)
    if (!hasAccess || hasAccess.count === 0) {
      return NextResponse.json({ error: '您没有权限删除此项目' }, { status: 403 })
    }

    // 开始删除项目相关数据
    // 1. 删除项目的所有 todo（包括相关的Audit记录）
    await todoQueries.deleteByProjectId.run(projectIdNum)
    
    // 2. 删除项目的所有成员关联
    await userProjectLinkQueries.deleteByProjectId.run(projectIdNum)
    
    // 3. 删除项目本身
    await projectQueries.delete.run(projectIdNum)

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error('删除项目失败:', error)
    return NextResponse.json({ error: '删除项目失败' }, { status: 500 })
  }
} 